package com.tianji.promotion.xxljob;

import com.tianji.promotion.entity.Coupon;
import com.tianji.promotion.enums.CouponStatus;
import com.tianji.promotion.service.ICouponService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author chengjy
 * @date 2023/6/5
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class TaskExecute {

    private final ICouponService    couponService;

    @XxlJob("taskExecutePromotion")
    public void taskExecutePromotion(){
        log.info("定时检测优惠券发放时间");
        //1.查询发放时间超过当前时间，并且状态为待发放的优惠券
        LocalDateTime now = LocalDateTime.now();
        List<Coupon> list = couponService.lambdaQuery()
                .eq(Coupon::getStatus, 2)
                .le(Coupon::getIssueBeginTime, now)
                .list();
        //2.直接退出
        if(list == null){
            return;
        }
        //3.修改为进行中
        list.forEach(po -> po.setStatus(CouponStatus.ISSUING));
        list.forEach(coupon -> log.info("发放优惠券：{}",coupon.getName()));
        this.couponService.updateBatchById(list);
    }


    @XxlJob("taskStopPromotion")
    public void taskStopPromotion(){
        log.info("定时结束优惠券活动");
        //1.查询结束时间超过当前时间，并且状态为进行中的优惠券
        LocalDateTime now = LocalDateTime.now();
        List<Coupon> list = couponService.lambdaQuery()
                .eq(Coupon::getStatus, 3)
                .le(Coupon::getIssueEndTime, now)
                .list();
        //2.直接退出
        if(list == null){
            return;
        }
        //3.修改为已结束
        list.forEach(po -> po.setStatus(CouponStatus.FINISHED));
        list.forEach(coupon -> log.info("发放优惠券：{}",coupon.getName()));
        this.couponService.updateBatchById(list);
    }
}
